/**
 * 上传文件到服务器
 */

const fs = require('fs');
const path = require('path');
const request = require('request');
const progress = require('request-progress');
const uuidv1 = require('uuid/v1');
const {
  basePath,
  createSign,
  turnURL
} = require('./util');
const { saveFile } = require('./dblink');


module.exports = function (req, res) {
    const file = req.files[0];
    const uuid = uuidv1(file.filename);
    const fileName = `${ uuid }${ encodeURI(file.originalname) }`;
    req.setTimeout(3600*1000*2);

    uploadFile(file, fileName).then(() => {
        saveFile({
            name: file.originalname,
            url: turnURL(fileName, true),
            timestamp: Date.now()
        }).then(rs => {
          const data = {
            id: rs.id,
            url: `/g/${fileName}`,
            uuid: uuid,
            fileName: file.originalname,
            size: file.size,
            type: file.mimetype
          };

          res.send(data);
        }).catch(err => {
          res.status(500).send({
            code: 500,
            err
          });
        });
    }).catch(err => {
        res.status(500).send({
            code: 500,
            err
        });
    });
}


/**
 * 上传文件到 讯达运
 * @param {*} file
 * @param {*} fileName
 */
function uploadFile(file, fileName) {
    const url = turnURL(fileName);
    const contentType = file.mimetype;
    const date = new Date().toUTCString();
    const size = file.size;
    const Authorization = createSign('PUT', contentType, url, date);
    const filePath = path.join(basePath, fileName);

    const headers = {
        Authorization,
        Date: date,
        'Content-Type': contentType,
        'Content-Length': size,
    };

    console.log(headers, turnURL(fileName, true));

    // 改名
    rename(file, fileName);

    return new Promise((resolve, reject) => {
        request({
            url: turnURL(fileName, true),
            headers,
            method: 'PUT',
            body: fs.createReadStream(filePath),
            encoding: null
        }, (error, response) => {
            if (error) {
                if (fs.existsSync(filePath)) {
                    fs.unlink(filePath);
                }
                console.error(error);
                reject(error);
                return;
            }

            resolve(response.body);

            // 上传完成后立即删除文件
            if (fs.existsSync(filePath)) {
                fs.unlink(filePath);
            }
        });
    });
}


/**
 * 改名
 * @param {*} file
 */
function rename(file, fileName) {
    const oldPath = path.join(basePath, file.filename);
    const newPath = path.join(basePath, fileName);

    return fs.renameSync(oldPath, newPath);
}
